import 'dart:convert';

import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_picker/picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:provider/provider.dart';
import 'package:taonile/config/config.dart';
import 'package:crypto/crypto.dart';
import '../entity/user_info_entity.dart';
import '../http/api.dart';
import '../provider/userinfo_provider.dart';
import '../routers/routers.dart';
import '../utils/double_utils.dart';
import '../utils/string_utils.dart';
import '../views/dialog_manager.dart';

///
/// 股票兑换
///
class MineStockExchange extends StatefulWidget {
  MineStockExchange({Key? key}) : super(key: key);

  @override
  State<MineStockExchange> createState() => _MineStockExchangeState();
}

class _MineStockExchangeState extends State<MineStockExchange> {
  var _num = '0';
  var resuntNum = '0';
  var payPwd = '';

  List<String> exchangeTypes = ['资产金券', '公益基金'];
  List<String> exchangeIds = ['vouchers', 'fund'];
  int typeIndex = 0;

  double stock_price = 0;
  double stock_rates = 0;
  double stock_fee = 0;
  double voucher_stock_rates = 0;
  double voucher_stock_fee = 0;

  @override
  void initState() {
    super.initState();
    getFees();
  }

  getFees() async {
    dynamic result = await Api.getSystemConfig();
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      setState(() {
        stock_price = double.parse(jsonResult['data']['stock_price']);
        stock_rates = double.parse(jsonResult['data']['stock_rates']);
        stock_fee = double.parse(jsonResult['data']['stock_fee']);
        voucher_stock_rates = double.parse(jsonResult['data']['voucher_stock_rates']);
        voucher_stock_fee = double.parse(jsonResult['data']['voucher_stock_fee']);
      });
    }
  }

  getRsultNum() {
    if (_num.isEmpty || _num == '0') {
      resuntNum = '0';
    }
    double num = 0;
    if (typeIndex == 0) {
      num = double.parse(_num) * voucher_stock_rates * stock_price;
    } else {
      num = double.parse(_num) * stock_rates * stock_price;
    }
    resuntNum = DoubleUtils.formartNum(num, 2);
  }

  confirm(BuildContext context) async {
    FocusManager.instance.primaryFocus?.unfocus();

    if (_num.isEmpty || _num == '0') {
      EasyLoading.showToast("请输入兑换数量");
      return;
    }

    if (!StringUtils.isFloatNum(_num)) {
      EasyLoading.showToast("请输入正确的数量");
      return;
    }

    // if (payPwd.length < 6) {
    //   EasyLoading.showToast("请输入6位数字支付密码");
    //   return;
    // }

    String isCheck = await checkPayPwd();
    if (isCheck == '1') {
      _showDialogForPinInput(context);
    } else {
      //请用户去设置支付密码
      DialogManager.showDefaultDialog(context, "你还未设置支付密码，请前往设置", () async {
        Routes.navigateTo(context, Routes.mineChangePassword, params: {'pageTitle': '修改支付密码'});
      });
    }
  }

  chooseGender(BuildContext context) async {
    Picker(
        adapter: PickerDataAdapter(pickerData: exchangeTypes, isArray: false),
        height: 300.w,
        headerDecoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.w),
            topRight: Radius.circular(20.w),
          ),
        ),
        itemExtent: 70.w,
        confirmText: '确定',
        cancelText: '取消',
        columnPadding: EdgeInsets.all(15.w),
        onConfirm: (picker, list) {
          // LogUtil.v(SingletonManager.instance.orderCancelReason[list[0]]);
          // postGender(list[0]);
          setState(() {
            typeIndex = list[0];
            getRsultNum();
          });
          print(exchangeTypes[typeIndex]);
        }).showModal(context, backgroundColor: Colors.transparent);
  }

  _showDialogForPinInput(context) {
    payPwd = '';
    AwesomeDialog(
      context: context,
      animType: AnimType.SCALE,
      dialogType: DialogType.NO_HEADER,
      body: Container(
        padding: EdgeInsets.only(top: 5.w, left: 20.w, right: 20.w),
        child: Column(
          children: [
            Text(
              "请输入支付密码",
              style: TextStyle(color: Config.colorText1, fontSize: 30.sp),
            ),
            Padding(
              padding: EdgeInsets.only(top: 30.w),
            ),
            PinCodeTextField(
              appContext: context,
              length: 6,
              obscureText: true,
              // controller: textEditingController,
              onChanged: (value) {},
              keyboardType: TextInputType.phone,
              onCompleted: (value) {
                payPwd = value;
              },
              // pinTheme: PinTheme(
              //   shape: PinCodeFieldShape.box, //输入框的形状
              //   borderRadius: const BorderRadius.all(Radius.circular(10)),
              //   // 其他可以设置可以自己参考，比如有输入文字的时候输入框是什么颜色，不能输入的时候是什么颜色等
              // ),
            ),
            InkWell(
              onTap: () {
                Routes.navigateTo(context, Routes.mineChangePassword,
                    params: {'pageTitle': '修改支付密码'});
              },
              child: Container(
                alignment: Alignment.centerRight,
                padding: EdgeInsets.only(right: 2.w),
                child: Text(
                  "忘记密码?",
                  style: TextStyle(
                      color: Config.colorText1,
                      fontSize: 25.sp,
                      decoration: TextDecoration.underline),
                ),
              ),
            ),
          ],
        ),
      ),
      title: '',
      desc: '',
      btnOkText: '确定',
      btnOkColor: Config.colorMain,
      btnOkOnPress: () {
        // print('oncompletd $payPwd');
        if (payPwd.isEmpty) {
          return;
        }
        transfer();
      },
    ).show();
  }

  transfer() async {
    var content = const Utf8Encoder().convert(payPwd);
    String md5pwd = "${md5.convert(content)}";

    dynamic result = await Api.stockExchange({
      'num': _num,
      'password': md5pwd,
      'type': exchangeIds[typeIndex],
    });
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("兑换成功");
      dynamic users = await Api.getUserinfo();
      Map<String, dynamic> resultUsers = Map.from(users);
      UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
      Provider.of<UserInfoProvider>(context, listen: false).changeUserinfo(infoEntity);
      Routes.router.pop(context, {'result': 1});
    }
  }

  checkPayPwd() async {
    dynamic result = await Api.checkSetPayPwd();
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      String pay_pwd_exists = jsonResult['data']['pay_pwd_exists'];
      return pay_pwd_exists;
    }
    return "0";
  }

  @override
  Widget build(BuildContext context) {
    UserInfoEntity infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: const Text('兑换股票'),
        centerTitle: true,
      ),
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Container(
          width: double.infinity,
          height: double.infinity,
          margin: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
          child: Column(
            children: [
              Container(
                width: double.infinity,
                height: 140.w,
                padding: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12.w),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      typeIndex == 0 ? '资产金券可用余额' : '公益基金可用余额',
                      style: TextStyle(fontSize: 24.sp, color: Config.colorText1),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 8.w),
                    ),
                    Text(
                      typeIndex == 0 ? infoEntity.data.assetVouchers : infoEntity.data.fundWallet,
                      style: TextStyle(
                          fontSize: 28.sp, color: Config.colorMain, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ),
              Container(
                width: double.infinity,
                padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                margin: EdgeInsets.only(top: 25.w),
                decoration: BoxDecoration(
                  color: (Config.colorWhite),
                  borderRadius: BorderRadius.circular(10.w),
                ),
                child: Column(
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          width: 130.w,
                          child: Text(
                            "兑换类型",
                            style: TextStyle(fontSize: 25.sp),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 30.w),
                        ),
                        SizedBox(
                          width: 490.w,
                          child: InkWell(
                            onTap: () {
                              chooseGender(context);
                            },
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(exchangeTypes[typeIndex],
                                    style: TextStyle(fontSize: 23.w, color: Config.colorText1)),
                                Padding(padding: EdgeInsets.all(10.w)),
                                Icon(Icons.arrow_forward_ios, size: 20.w),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                    Divider(
                      color: Config.colorDivider,
                      height: 40.w,
                      thickness: 2.w,
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          width: 130.w,
                          child: Text(
                            "兑换比例",
                            style: TextStyle(fontSize: 25.sp),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 30.w),
                        ),
                        Text(
                          "股票实时价格 1：${typeIndex == 0 ? voucher_stock_rates : stock_rates}${typeIndex == 0 ? '资产金券' : '公益基金'}",
                          style: TextStyle(fontSize: 25.sp),
                        ),
                      ],
                    ),
                    Divider(
                      color: Config.colorDivider,
                      height: 40.w,
                      thickness: 2.w,
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          width: 130.w,
                          child: Text(
                            "兑换股数",
                            style: TextStyle(fontSize: 25.sp),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 30.w),
                        ),
                        Row(
                          children: [
                            Container(
                              width: 280.w,
                              margin: EdgeInsets.symmetric(vertical: 5.w),
                              child: TextField(
                                keyboardType: TextInputType.number,
                                textAlign: TextAlign.justify,
                                obscureText: false,
                                maxLength: 10,
                                maxLines: 1,
                                onChanged: (value) {
                                  setState(() {
                                    _num = value;
                                    getRsultNum();
                                  });
                                },
                                inputFormatters: [
                                  FilteringTextInputFormatter.allow(RegExp("[0-9]")),
                                ],
                                style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                                decoration: const InputDecoration(
                                  hintStyle: TextStyle(color: Config.colorText3),
                                  hintText: "请输入兑换股票数量",
                                  counterText: '',
                                  isDense: true,
                                  border: InputBorder.none,
                                  contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                                ),
                              ),
                            ),
                            Container(
                              width: 220.w,
                              alignment: Alignment.centerRight,
                              child: Text(
                                "≈$resuntNum${typeIndex == 0 ? '资产金券' : '公益基金'}",
                                style: TextStyle(fontSize: 20.sp),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    Divider(
                      color: Config.colorDivider,
                      height: 40.w,
                      thickness: 2.w,
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          width: 130.w,
                          child: Text(
                            "兑换手续费",
                            style: TextStyle(fontSize: 25.sp),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 30.w),
                        ),
                        Text(
                          typeIndex == 0
                              ? DoubleUtils.formartNum(
                                  double.parse(resuntNum) * voucher_stock_fee, 2)
                              : DoubleUtils.formartNum(double.parse(resuntNum) * stock_fee, 2),
                          style: TextStyle(fontSize: 25.sp),
                        ),
                        Expanded(
                          child: Text(
                            typeIndex == 0 ? "${voucher_stock_fee * 100}%" : "${stock_fee * 100}%",
                            textAlign: TextAlign.right,
                            style: TextStyle(fontSize: 25.sp),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Container(
                width: 750.w,
                height: 100.w,
                padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 8.w),
                margin: EdgeInsets.only(top: 45.w),
                child: ElevatedButton(
                  clipBehavior: Clip.antiAlias,
                  onPressed: () => {confirm(context)},
                  style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                  child: const Text('确定'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
